package com.jmb.jdbc02;

import javax.xml.transform.Result;
import java.sql.*;
import java.util.stream.Stream;

public class JdbcUtils {
    // 首先我们要定义我们的不可改变的常量，因为连接信息不会被改变。
    public static final String DRIVERNAME="com.mysql.cj.jdbc.Driver";
    public static final String url="jdbc:mysql://rm-uf6156pf2gvr40458ro.mysql.rds.aliyuncs.com:3306/home-lagou-demo?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true";
    public static final String user="jinbo";
    public static final String password="Ly521521";

    // 这个地方我写一个静态代码块，表达我们这个类被调用他就会创建数据库的链接
    static {
        try {
            Class.forName(DRIVERNAME);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    // 获取地址
    public static Connection getConnection(){
        try {
            Connection connection =  DriverManager.getConnection(url,user,password);
            return connection;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            return null;
        }

    }
    // 关闭资源
    public static void close(Connection con , Statement statement){
        if (con!=null&&statement!=null){
            try {
                statement.close();
                con.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }else {
            System.out.println("链接为空");
        }

    }
    // 关闭连接和查询语句
    public static void close(Connection connection, Statement statement , ResultSet resultSet){
        if (connection!=null&&statement!=null){
            try {
                resultSet.close();
                statement.close();
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }

        }
        else {
            System.out.println("链接和查询都为空");
        }
    }
}
